package com.spring.future.common.config;

import com.spring.VueApplication;
import com.spring.future.common.utils.StringUtils;
import com.spring.future.common.utils.ThreadLocalContext;
import com.spring.future.modules.sys.domain.Account;
import com.spring.future.modules.sys.security.CustomUserDetails;
import com.spring.future.modules.sys.service.AccountService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by liuj on 2016-08-20.
 */
public class MyHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Account account= null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal().getClass().isAssignableFrom(CustomUserDetails.class)) {
            account =  ((CustomUserDetails) authentication.getPrincipal()).getAccount();
        } else {
            if(request.getParameter("accountId")!=null) {
                String accountId = StringUtils.toString(request.getParameter("accountId"));
                account = VueApplication.getApplicationContext().getBean(AccountService.class).findOne(accountId);
            }
        }
        ThreadLocalContext.get().setAccount(account);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalContext.get().remove();
    }
}